//
//  PhotoViewController.m
//  Dispatch
//
//  Created by hyeyeon on 14. 1. 21..
//  Copyright (c) 2014년 hyeyeon. All rights reserved.
//

#import "PhotoViewController.h"

#define framePhoto(index)   CGRectMake((mySize.width)*(index), 0, mScrollView.frame.size.width, mScrollView.frame.size.height)

#define frameSDK(index)  CGRectMake((mySize.width)*(index), myOrginY, mySize.width, mySize.height-20)


#define frameSDK_L  CGRectMake(-mySize.width, myOrginY, mySize.width, mySize.height-20)
#define frameSDK_R  CGRectMake(mySize.width, myOrginY, mySize.width, mySize.height-20)
#define frameSDK_C  CGRectMake(0, myOrginY, mySize.width, mySize.height-20)

@interface PhotoViewController ()

@end

@implementation PhotoViewController
@synthesize issuesList, issueFirstIndex, issueLastIndex, responseData, imageURL, typeHotIssue, mDelegate, currentDate, secondView, parentClassIndex, mTwitter, adCount, currentAdCount, dateString, currentImageIndex;
@synthesize analyticsAction, analyticsLabelDetail, analyticsLabelWhole;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        FBLoginView *loginview = [[FBLoginView alloc] init];
        loginview.delegate = self;
        
        appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        self.responseData = [NSMutableData data];
        dataList = [[NSMutableArray alloc] init];
        mImageDic = [[NSMutableDictionary alloc] init];
        
        imageList = [[NSMutableArray alloc] init];
        currentImageIndex = 0;
        currentAdCount = 0;
        
        
        UIImageView *dImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"thumb_default"]];
        [dImage sizeToFit];
        dImage.center = CGPointMake(mySize.width*0.5f, mySize.height*0.5f);
        [self.view addSubview:dImage];
        
        
        // Custom initialization
        [self makeScrollView];
        [self makeTitleView];
        [self makeContentView];
        [self makeBottemView];
        
        
        mActivityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        mActivityView.center = CGPointMake(mySize.width*0.5f, mySize.height*0.5f+50);
        [self.view addSubview:mActivityView];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.view.backgroundColor = ColorFromRGB(0x373339);
    
    if (deviceIOS7) {
        UIView *statusView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mySize.width, myStatusBarHeight)];
        statusView.backgroundColor = ColorFromRGB(0x373339);
        statusView.alpha = 0.7f;
        [self.view addSubview:statusView];
    }
    
    //facebook
    
    FBLoginView *loginview = [[FBLoginView alloc] init];
    loginview.delegate = self;
    
    
    NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
    [notification addObserver:self selector:@selector(loadItemLoad:) name:ITEM_LIST_LOAD object:nil];
    
    
}

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
//    loadIndex = self.currentIssueIndex;
    
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:ITEM_LIST_LOAD object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 스크롤
-(void)makeScrollView{
    
    //스크롤
    mScrollView = [[PhotoScrollView alloc] initWithFrame:CGRectMake(0, myOrginY, mySize.width, mySize.height-20)];
    mScrollView.delegate = self;
    mScrollView.parent = self;
    mScrollView.minimumZoomScale = 1.0f;
    mScrollView.maximumZoomScale = 4.0f;
    mScrollView.clipsToBounds = YES;
    mScrollView.bounces = YES;
    mScrollView.scrollEnabled = YES;
    mScrollView.pagingEnabled = YES;
    mScrollView.showsHorizontalScrollIndicator = NO;
    mScrollView.showsVerticalScrollIndicator = NO;
    [mScrollView setContentSize:CGSizeMake(mySize.width*3, mScrollView.frame.size.height)];
    mScrollView.backgroundColor = [UIColor clearColor];
    currentScrollContentSize = mySize.width*3;
    
    [self.view addSubview:mScrollView];

    
    firstView = [[UIView alloc] initWithFrame:CGRectMake(-mySize.width, 0, mScrollView.frame.size.width, mScrollView.frame.size.height)];
    [mScrollView addSubview:firstView];
    
    thirdView = [[UIView alloc] initWithFrame:CGRectMake(mySize.width, 0, mScrollView.frame.size.width, mScrollView.frame.size.height)];
    [mScrollView addSubview:thirdView];
    
    secondView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mScrollView.frame.size.width, mScrollView.frame.size.height)];
    [mScrollView addSubview:secondView];
    
    //디폴트뷰 올리기
//    for (int i = 0; i<3; i++) {
//        
//        UIImageView *dImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"thumb_default"]];
//        [dImage sizeToFit];
//        dImage.center = CGPointMake(mScrollView.frame.size.width*0.5f, mScrollView.frame.size.height*0.5f);
//        
//        if (i == 0) {
//            [firstView addSubview:dImage];
//        }else if (i == 1){
//            [secondView addSubview:dImage];
//        }else{
//            [thirdView addSubview:dImage];
//        }
//    }
    
    

    //이미지뷰 올리기
    fImage = [[UIImageView alloc] initWithFrame:CGRectZero];
    [firstView addSubview:fImage];
    
    sImage = [[UIImageView alloc] initWithFrame:CGRectZero];
    [secondView addSubview:sImage];
    
    tImage = [[UIImageView alloc] initWithFrame:CGRectZero];
    [thirdView addSubview:tImage];
    
    
    
    //화살표 생성
    leftArrowButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 85)];
    [leftArrowButton setImage:[UIImage imageNamed:@"btn_arrow_l2"] forState:UIControlStateNormal];
    [leftArrowButton addTarget:self action:@selector(leftArrowButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    leftArrowButton.center = CGPointMake(leftArrowButton.center.x, mySize.height*0.5f);
    [self.view addSubview:leftArrowButton];
    
    rightArrowButton = [[UIButton alloc] initWithFrame:CGRectMake(mySize.width-60, 0, 50, 85)];
    [rightArrowButton setImage:[UIImage imageNamed:@"btn_arrow_r2"] forState:UIControlStateNormal];
    [rightArrowButton addTarget:self action:@selector(rightArrowButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    rightArrowButton.center = CGPointMake(rightArrowButton.center.x, mySize.height*0.5f);
    [self.view addSubview:rightArrowButton];
    
}

#pragma mark - 화살표

-(void)leftArrowButtonAction:(id)sender{
    
    if (zooming) {
        mScrollView.zoomScale = 1.0f;
        
        zooming = NO;
        [mScrollView setContentSize:CGSizeMake(currentScrollContentSize, mScrollView.frame.size.height)];
        secondView.frame = framePhoto(currentImageIndex);
        [mScrollView setContentOffset:CGPointMake(currentImageIndex*mySize.width, 0)];
        
    }
    
    if (prevPageIsMan) {
        NSLog(@"버튼 : 광고띄움 이전");
        [self makeManBreakInImageViewComeLeft:YES];
        return;
        
    }
    
    
    if (currentImageIndex-1 < 0) {
        if (self.parentClassIndex == 6) {
            //스타랭킹일경우엔 요청할 이전데이타가 없으므로(무조건0부터의 데이터가 나옴)부를필요없음
            
            [appDelegate alertViewWithMessage:NSLocalizedString(@"First page", @"") andTimeInterval:2.0f];
            return;
        }
        requestType = RequestPrevious;
        [self addRequestDataNext:NO];
    }else{
        
        [mScrollView setContentOffset:CGPointMake(mScrollView.contentOffset.x-mySize.width, 0) animated:YES];
        currentImageIndex--;
        
        [self settingPageToNext:NO];
    }

}

-(void)rightArrowButtonAction:(id)sender{
    
    if (zooming) {
        mScrollView.zoomScale = 1.0f;
        
        zooming = NO;
        [mScrollView setContentSize:CGSizeMake(currentScrollContentSize, mScrollView.frame.size.height)];
        secondView.frame = framePhoto(currentImageIndex);
        [mScrollView setContentOffset:CGPointMake(currentImageIndex*mySize.width, 0)];
        
    }
    
    if (nextPageIsMan) {
        NSLog(@"버튼 : 광고띄움 다음");
        [self makeManBreakInImageViewComeLeft:NO];
        return;
    }
    
    if (currentImageIndex+1 >= [dataList count]) {
        
        requestType = RequestNext;
        [self addRequestDataNext:YES];
    }else{
        
        [mScrollView setContentOffset:CGPointMake(mScrollView.contentOffset.x+mySize.width, 0) animated:YES];
        currentImageIndex++;
        [self settingPageToNext:YES];
        
    }
    
}

#pragma mark - 타이틀

-(void)makeTitleView{
    
    titleView = [[UIView alloc] initWithFrame:CGRectMake(0, myOrginY, mySize.width, 44)];
    [self.view addSubview:titleView];
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, titleView.frame.size.width, titleView.frame.size.height-1)];
    bgView.backgroundColor = ColorFromRGB(0x373339);
    bgView.alpha = 0.7f;
    [titleView addSubview:bgView];
    
    UIView *bgView2 = [[UIView alloc] initWithFrame:CGRectMake(0, bgView.frame.origin.y+bgView.frame.size.height, bgView.frame.size.width, 1)];
    bgView2.backgroundColor = ColorFromRGB(0x373339);
    [titleView addSubview:bgView2];
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 0, 37, 44)];
    [backButton setImage:[UIImage imageNamed:@"btn_back01"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:backButton];
    
    starButton = [[UIButton alloc] initWithFrame:CGRectMake(mySize.width-70, 11, 60, 44)];
    [starButton addTarget:self action:@selector(starButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:starButton];
    
    starNameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    starNameLabel.backgroundColor = [UIColor clearColor];
    starNameLabel.textColor = ColorFromRGB(0xffffff);
    starNameLabel.font = [UIFont systemFontOfSize:15];
    [starButton addSubview:starNameLabel];
    
    goStarImage = [[UIImageView alloc] initWithFrame:CGRectZero];
    goStarImage.image = [UIImage imageNamed:@"btn_star_home"];
    [starButton addSubview:goStarImage];
    
    titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(backButton.frame.origin.x+backButton.frame.size.width+10, 0, mySize.width-starButton.frame.origin.x-starButton.frame.size.width, 44)];
    titleLabel.font = [UIFont systemFontOfSize:15];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [titleView addSubview:titleLabel];
    
}


-(void)setTitleIndex:(NSInteger)index{
    
    currentImageIndex = index;
    starNameLabel.text = [[dataList objectAtIndex:index] objectForKey:@"name"];
    
    NSString *title = [[dataList objectAtIndex:index] objectForKey:@"title"];
    if (title) {
        title = [[dataList objectAtIndex:index] objectForKey:@"name"];
    }
    [self setTitleText:title];
}

-(void)setTitleText:(NSString*)text{
    
    //스타이름가져오면 스타버튼 샛팅
    [starNameLabel sizeToFit];
    starNameLabel.frame = CGRectMake(0, 0, starNameLabel.frame.size.width, 44);
    goStarImage.frame = CGRectMake(starNameLabel.frame.origin.x+starNameLabel.frame.size.width+5, 0,23, 44);
    starButton.frame = CGRectMake(mySize.width-10-goStarImage.frame.size.width-5-starNameLabel.frame.size.width,
                                  0,
                                  starNameLabel.frame.size.width+5+goStarImage.frame.size.width,
                                  44);
    
    titleLabel.text = text;
    titleLabel.frame = CGRectMake(42, 0, mySize.width-42-starButton.frame.size.width-10, 44);
}

#pragma mark - 순위

-(void)makeRankingLabel{
    rankingLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    rankingLabel.font = [UIFont italicSystemFontOfSize:60];
    rankingLabel.backgroundColor = [UIColor clearColor];
    rankingLabel.shadowColor = ColorFromRGB(0x000000);
    rankingLabel.textColor = ColorFromRGB(0xffffff);
    [secondView addSubview:rankingLabel];
}

-(void)setRankingLabel:(NSInteger)index{
    
    if (!rankingLabel) {
        [self makeRankingLabel];
    }
    
    currentImageIndex = index;
    NSString *string = [[dataList objectAtIndex:index] objectForKey:@"ranking"];
    rankingLabel.text = string;
    [rankingLabel sizeToFit];
    rankingLabel.frame = CGRectMake(mySize.width-10-rankingLabel.frame.size.width, 10, rankingLabel.frame.size.width, rankingLabel.frame.size.height);
}


#pragma mark 뒤로

-(void)backButtonAction:(id)sende{
    [appDelegate removeActivity];
    [self dismissModalViewControllerAnimated:YES];
    
}

#pragma mark 스타홈

-(void)starButtonAction:(id)sender{
    
    if (currentImageIndex < [dataList count]) {
        [appDelegate analyticsCategory:ANA_CAT_CLICK Action:ANA_ACT_COMMON Label:ANA_LAB_C_Starhome];
        NSString *starID = [[dataList objectAtIndex:currentImageIndex] objectForKey:@"star_id"];
        
        ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
        [self dismissViewControllerAnimated:NO completion:^{
            [viewController appearStarListToID:starID];
        }];
    }
    
}

#pragma mark - 하단 메뉴

-(void)makeBottemView{
    
    float gap = deviceIOS7 ? 0 : 20;
    
    bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, mySize.height-50-gap, mySize.width, 50)];
    [self.view addSubview:bottomView];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, bottomView.frame.size.width, 1)];
    line.backgroundColor = ColorFromRGB(0x646166);
    [bottomView addSubview:line];
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, bottomView.frame.size.width, bottomView.frame.size.height-1)];
    bgView.backgroundColor = ColorFromRGB(0x282529);
    bgView.alpha = 0.9f;
    [bottomView addSubview:bgView];
    
    //menu
    UIButton *saveButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 50)];
    [saveButton setImage:[UIImage imageNamed:@"btn_save"] forState:UIControlStateNormal];
    [saveButton addTarget:self action:@selector(saveButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:saveButton];
    
    UIButton *shareButton = [[UIButton alloc] initWithFrame:CGRectMake(saveButton.frame.origin.x+saveButton.frame.size.width, 0, saveButton.frame.size.width, saveButton.frame.size.height)];
    [shareButton setImage:[UIImage imageNamed:@"btn_share"] forState:UIControlStateNormal];
    [shareButton addTarget:self action:@selector(shareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:shareButton];
    
    thirdBtnRect = CGRectMake(shareButton.frame.origin.x+shareButton.frame.size.width, shareButton.frame.origin.y, shareButton.frame.size.width, shareButton.frame.size.height);
}

-(void)makeUpAndDownButtonWithFirstFrame:(CGRect)rect{
    //up&down
    upButton = [[UIButton alloc] initWithFrame:rect];
    [upButton setImage:[UIImage imageNamed:@"btn_up"] forState:UIControlStateNormal];
    [upButton setImage:[UIImage imageNamed:@"btn_up_on"] forState:UIControlStateSelected];
    [upButton addTarget:self action:@selector(upButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:upButton];
    
    downButton = [[UIButton alloc] initWithFrame:CGRectMake(rect.origin.x+rect.size.width, rect.origin.y, rect.size.width, rect.size.height)];
    [downButton setImage:[UIImage imageNamed:@"btn_down"] forState:UIControlStateNormal];
    [downButton setImage:[UIImage imageNamed:@"btn_down_on"] forState:UIControlStateSelected];
    [downButton addTarget:self action:@selector(downButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:downButton];
    
    upCountLabel = [[UILabel alloc] initWithFrame:CGRectMake(38, 0, upButton.frame.size.width, upButton.frame.size.height)];
    upCountLabel.textAlignment = NSTextAlignmentLeft;
    upCountLabel.textColor = ColorFromRGB(0x49a1d9);
    upCountLabel.font = [UIFont systemFontOfSize:12];
    upCountLabel.backgroundColor = [UIColor clearColor];
    [upButton addSubview:upCountLabel];
    
    downCountLabel = [[UILabel alloc] initWithFrame:upCountLabel.frame];
    downCountLabel.textAlignment = NSTextAlignmentLeft;
    downCountLabel.textColor = ColorFromRGB(0x49a1d9);
    downCountLabel.font = upCountLabel.font;
    downCountLabel.backgroundColor = [UIColor clearColor];
    [downButton addSubview:downCountLabel];
}

-(void)makeWinAndLoseButtonWithFirstFrame:(CGRect)rect{
    
    //win&lose
    UIButton *winButton = [[UIButton alloc] initWithFrame:rect];
    [winButton addTarget:self action:@selector(winButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:winButton];
    
    UIButton *loseButton = [[UIButton alloc] initWithFrame:CGRectMake(winButton.frame.origin.x+winButton.frame.size.width, rect.origin.y, rect.size.width, rect.size.height)];
    [loseButton addTarget:self action:@selector(loseButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:loseButton];
    
//    winButton.backgroundColor = [UIColor redColor];
//    loseButton.backgroundColor = [UIColor blueColor];
    
    
    UILabel *winBtnTitle = [[UILabel alloc] initWithFrame:CGRectMake(11, 0, 30, winButton.frame.size.height)];
    winBtnTitle.text = @"WIN";
    winBtnTitle.textColor = ColorFromRGB(0x55bcfd);
    winBtnTitle.font = [UIFont fontWithName:@"Verdana-BoldItalic" size:12];
    [winBtnTitle sizeToFit];
    [winButton addSubview:winBtnTitle];
    winBtnTitle.center = CGPointMake(winBtnTitle.center.x, loseButton.frame.size.height*0.5f);
    
    UILabel *loseBtnTitle = [[UILabel alloc] initWithFrame:CGRectMake(11, 0, 30, loseButton.frame.size.height)];
    loseBtnTitle.textColor = ColorFromRGB(0xd74040);
    loseBtnTitle.text = @"LOSE";
    loseBtnTitle.font = winBtnTitle.font;
    [loseBtnTitle sizeToFit];
    [loseButton addSubview:loseBtnTitle];
    loseBtnTitle.center = CGPointMake(loseBtnTitle.center.x, winBtnTitle.center.y);
    
    winCountLabel = [[UILabel alloc] initWithFrame:CGRectMake(winBtnTitle.frame.origin.x+winBtnTitle.frame.size.width+5, 0, winButton.frame.size.width-(winBtnTitle.frame.origin.x+winBtnTitle.frame.size.width+5), winButton.frame.size.height)];
    winCountLabel.textColor = ColorFromRGB(0xffffff);
    winCountLabel.font = [UIFont systemFontOfSize:12];
    [winButton addSubview:winCountLabel];
    
    loseCountLabel = [[UILabel alloc] initWithFrame:CGRectMake(loseBtnTitle.frame.origin.x+loseBtnTitle.frame.size.width+5, 0, loseButton.frame.size.width-(loseBtnTitle.frame.origin.x+loseBtnTitle.frame.size.width+5), loseButton.frame.size.height)];
    loseCountLabel.textColor = ColorFromRGB(0xffffff);
    loseCountLabel.font = winCountLabel.font;
    [loseButton addSubview:loseCountLabel];

}




#pragma mark 저장
-(void)saveButtonAction:(id)sender{
    SaveImgViewController *sController = [[SaveImgViewController alloc] init];
    [sController initSetImage:sImage.image frame:sImage.frame];
    
    [self presentViewController:sController animated:YES completion:nil];
}

#pragma mark 공유
-(void)shareButtonAction:(id)sender{
    [self makeActionSheetTitle:@"sns share"];
}

-(void)makeActionSheetTitle:(NSString*)title{
    
    NSString *fbTitle = enableFacebook ? @"Facebook" : @"Facebook Login";
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:title delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Kakao Talk",@"Kakao Story",fbTitle,@"Twitter", nil];
    [actionSheet showInView:self.view];
}


#pragma mark 올려&내려
-(void)upButtonAction:(id)sender{

    if ([self checkUpDown]) {
        
        NSString *issueID = [[dataList objectAtIndex:currentImageIndex] objectForKey:@"issue_id"];
        [self requestUp:YES andIssueID:issueID];
    }else{
        [appDelegate alertViewWithMessage:NSLocalizedString(@"upOrDownFail", @"") andTimeInterval:2.0f];
    }
    
}

-(void)downButtonAction:(id)sender{
    
    if ([self checkUpDown]) {
        
        NSString *issueID = [[dataList objectAtIndex:currentImageIndex] objectForKey:@"issue_id"];
        [self requestUp:NO andIssueID:issueID];
    }else{
        
        [appDelegate alertViewWithMessage:NSLocalizedString(@"upOrDownFail", @"") andTimeInterval:2.0f];
    }
}

-(void)setCountUpandDown:(NSInteger)index{
    
    NSString *up = [[dataList objectAtIndex:index] objectForKey:@"up_cnt"];
    NSString *down = [[dataList objectAtIndex:index] objectForKey:@"down_cnt"];
    [self setUp:up andDown:down];
}

-(void)setUp:(NSString*)up andDown:(NSString*)down{
    
    if (!upCountLabel) {
        [self makeUpAndDownButtonWithFirstFrame:thirdBtnRect];
    }
    NSLog(@"up : %@ | down : %@",up,down);
    
    upButton.selected = downButton.selected = NO;
    
    //데이타 부르고 나서 업다운하면 데이타가 +1이 되어있을거임
    NSString *issueID = [[dataList objectAtIndex:currentImageIndex] objectForKey:@"issue_id"];
    if ([upDownTSDic objectForKey:issueID]) {
        NSInteger num = [[upDownTSDic objectForKey:issueID] integerValue];
        
        if (num == 1) {
            up = [NSString stringWithFormat:@"%d", [up integerValue]+1];
            upButton.selected = YES;
        }else{
            down = [NSString stringWithFormat:@"%d",[down integerValue]+1];
            downButton.selected = YES;
        }
    }
    
    NSInteger voteStatus = [[[dataList objectAtIndex:currentImageIndex] objectForKey:@"vote_status"] integerValue];
    
    if (voteStatus == 1) {
        upButton.selected = YES;
    }else if(voteStatus == 2){
        downButton.selected = YES;
    }

    
    upCountLabel.text = up;
    downCountLabel.text = down;
}

-(BOOL)checkUpDown{
    
    NSDictionary *dic = [dataList objectAtIndex:currentImageIndex];
    NSInteger participation = [[dic objectForKey:@"vote_status"] integerValue];
    if (participation > 0) {
        return NO;
    }else{
        if (upDownTSDic) {
            NSString *key = [dic objectForKey:@"issue_id"];

            if ([upDownTSDic objectForKey:key]) {
                return NO;
            }else{
                return YES;
            }
            
        }else{
            return YES;
        }
    }
}

#pragma mark - win&lose
-(void)winButtonAction:(id)sender{
    
}

-(void)loseButtonAction:(id)sender{
    
}

-(void)setCountWinAndLose:(NSInteger)index{
    NSString *win = [[dataList objectAtIndex:index] objectForKey:@"win_cnt"];
    NSString *lose = [[dataList objectAtIndex:index] objectForKey:@"lose_cnt"];
    [self setWin:win andLose:lose];
}

-(void)setWin:(NSString*)win andLose:(NSString*)lose{

    if (!winCountLabel) {
        [self makeWinAndLoseButtonWithFirstFrame:thirdBtnRect];
    }
    winCountLabel.text = win;
    loseCountLabel.text = lose;
    
}


#pragma mark - 기사보기 뷰

-(void)makeContentView{
    
    float originY = deviceIOS7 ? mySize.height-50-100 : mySize.height-50-100-20;
    
    contentView = [[UIView alloc] initWithFrame:CGRectMake(0, originY, mySize.width, 100)];
    [self.view addSubview:contentView];
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, contentView.frame.size.width, contentView.frame.size.height)];
    bgView.backgroundColor = ColorFromRGB(0x373339);
    bgView.alpha = 0.85f;
    [contentView addSubview:bgView];
    
    //원문보기 버튼
    NSString *buttenString = NSLocalizedString(@"news", @"");
    UIButton *contentButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, (buttenString.length*12), 20)];
    contentButton.layer.cornerRadius = 10;
    contentButton.layer.borderColor = ColorFromRGB(0x5db9f7).CGColor;
    contentButton.layer.borderWidth = 1;
    [contentButton.titleLabel setFont:[UIFont systemFontOfSize:13]];
    [contentButton setTitle:buttenString forState:UIControlStateNormal];
    [contentButton setTitleColor:ColorFromRGB(0x5db9f7) forState:UIControlStateNormal];
    [contentButton addTarget:self action:@selector(contentButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:contentButton];
    
    //날짜
    dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(contentView.frame.size.width-10, 10, 100, 20)];
    dateLabel.textColor = ColorFromRGB(0xffffff);
    dateLabel.font = [UIFont systemFontOfSize:12];
    dateLabel.textAlignment = NSTextAlignmentRight;
    dateLabel.backgroundColor = [UIColor clearColor];
    [contentView addSubview:dateLabel];
    
    //원문
    contentTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, contentButton.frame.origin.y+contentButton.frame.size.height+3, mySize.width-20, contentView.frame.size.height-contentButton.frame.origin.y-contentButton.frame.size.height-6)];
    [contentView addSubview:contentTextView];
    contentTextView.backgroundColor = [UIColor clearColor];
    contentTextView.textColor = ColorFromRGB(0xffffff);
    contentTextView.editable = NO;
    contentTextView.font = [UIFont systemFontOfSize:12];
}

-(void)contentButtonAction:(id)sender{
    

    [appDelegate analyticsCategory:ANA_CAT_CLICK Action:ANA_ACT_COMMON Label:ANA_LAB_C_Newslink];
    
    NewsViewController *news = [[NewsViewController alloc] init];
    NSURL *url = [NSURL URLWithString:[[dataList objectAtIndex:currentImageIndex] objectForKey:@"news_url"]];
    
    
    [news setNewsTitle:nil andURL:url];
    
    [self presentModalViewController:news animated:YES];
}

-(void)setContentIndex:(NSInteger)index{
    
    dateLabel.text = [[dataList objectAtIndex:index] objectForKey:@"date"];
    [dateLabel sizeToFit];
    dateLabel.frame = CGRectMake(contentView.frame.size.width-10-dateLabel.frame.size.width, 25-dateLabel.frame.size.height, dateLabel.frame.size.width, dateLabel.frame.size.height);
    
    NSString *caption = [[dataList objectAtIndex:index] objectForKey:@"caption"];
    caption = [appDelegate stringByHTMLEncodingWithString:caption];
    
    if ([appDelegate checkObject:caption]) {
        
        contentTextView.text = caption;
        float originY = deviceIOS7 ? mySize.height-50-100 : mySize.height-50-100-20;
        contentView.frame = CGRectMake(0, originY, mySize.width, 100);
        
    }else{
        contentTextView.text = nil;
        float originY = deviceIOS7 ? mySize.height-50-25 : mySize.height-50-25-20;
        contentView.frame = CGRectMake(0, originY, mySize.width, 25);
    }
    
}

#pragma mark - 인덱스
-(void)setIssueIndex:(NSInteger)index{
    self.issueLastIndex = index;
    self.issueFirstIndex = index;
    loadIndex = index;
}


#pragma mark - SNS
//어플 설치여부 검사
-(BOOL)applicationCanOpenURL:(NSString*)urlString{
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]];
}

//공유할내용
-(NSString*)shareOfDate{
    NSString *dStr = [[dataList objectAtIndex:currentImageIndex] objectForKey:@"date"];
    return [NSString stringWithFormat:@"[Dispatch] %@",dStr];
}

-(NSString*)shareOfIssueTitle{
    return [[dataList objectAtIndex:currentImageIndex] objectForKey:@"title"];
}

-(NSString*)shareOfIssueCaption{
    NSString *caption = [[dataList objectAtIndex:currentImageIndex] objectForKey:@"caption"];
    return [appDelegate stringByHTMLEncodingWithString:caption];
}

-(NSString*)shareOfNewsURL{
    
    NSString *string = nil;
//
//    if (self.parentClassIndex == 1) {
        //배틀외
        string = [[dataList objectAtIndex:currentImageIndex] objectForKey:@"issue_id"];
        string = [NSString stringWithFormat:@"http://dispatch.appvista.com/news/?is=%@",string];
        return string;
//    }else if(self.parentClassIndex == 2){
//        //배틀
//        return nil; //아직작업안함
//    }else{
//        return nil;
//    }
}

-(NSString*)shareSchemeOpen{
    
    NSString *string = [[dataList objectAtIndex:currentImageIndex] objectForKey:@"issue_id"];
    string = [NSString stringWithFormat:@"dispatch://launch?sid=%@&c=i",string];
    
    return string;
}

#pragma mark 카카오톡
-(void)goKakaoTalk{
    if ([KakaoLinkCenter canOpenKakaoLink]) {
        
        
        NSMutableArray *metaInfoArray = [NSMutableArray array];
        
        NSDictionary *metaInfoAndroid = [NSDictionary dictionaryWithObjectsAndKeys:
                                         @"android", @"os",
                                         @"phone", @"devicetype",
                                         androidURL, @"installurl",
                                         [self shareSchemeOpen], @"executeurl",
                                         nil];
        
        NSDictionary *metaInfoIOS = [NSDictionary dictionaryWithObjectsAndKeys:
                                     @"ios", @"os",
                                     @"phone", @"devicetype",
                                     ituneURL, @"installurl",
                                     [self shareSchemeOpen], @"executeurl",
                                     nil];
        
        [metaInfoArray addObject:metaInfoAndroid];
        [metaInfoArray addObject:metaInfoIOS];
        
        [KakaoLinkCenter openKakaoAppLinkWithMessage:[NSString stringWithFormat:@"%@\n%@\n%@",[self shareOfIssueTitle],[self shareOfIssueCaption],[self shareOfNewsURL]]
                                                 URL:[self shareOfNewsURL]
                                         appBundleID:[[NSBundle mainBundle] bundleIdentifier]
                                          appVersion:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]
                                             appName:@"Dispatch"
                                       metaInfoArray:metaInfoArray];
    }else{
        //설치 안되어있음
    }
}

#pragma mark 카카오스토리
-(void)goKakaoStory{
    if ([KakaoLinkCenter canOpenStoryLink]) {
        
        
        [KakaoLinkCenter openStoryLinkWithPost:[NSString stringWithFormat:@"%@\n%@\n%@",[self shareOfIssueTitle],[self shareOfIssueCaption],[self shareOfNewsURL]]
                                   appBundleID:[[NSBundle mainBundle] bundleIdentifier]
                                    appVersion:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]
                                       appName:@"Dispatch"
                                       urlInfo:nil];
    }else{
        //설치 안되어있음
    }
}

#pragma mark 페이스북
-(void)goFaceBook{
    
    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
        
        NSString *text = [NSString stringWithFormat:@"%@\n%@",[self shareOfIssueTitle],[self shareOfIssueCaption]];
        
        SLComposeViewController *facebook = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
        [facebook setInitialText:text];
        [facebook addURL:[NSURL URLWithString:[self shareOfNewsURL]]];
        [self presentViewController:facebook animated:YES completion:nil];
        
    }else{
        
        NSURL *urlToShare = [NSURL URLWithString:[self shareOfNewsURL]];
        
        FBShareDialogParams *shareParams = [[FBShareDialogParams alloc] init];
        shareParams.link = urlToShare;
        shareParams.name = [self shareOfIssueTitle];
        shareParams.description = [self shareOfIssueCaption];
        
        // If the Facebook app is installed and we can present the share dialog
        if ([FBDialogs canPresentShareDialogWithParams:shareParams]) {
            // Present the share dialog
            [FBDialogs presentShareDialogWithLink:shareParams.link
                                             name:shareParams.name
                                          caption:shareParams.caption
                                      description:shareParams.description
                                          picture:shareParams.picture
                                      clientState:nil
                                          handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
                                              if(error) {
                                                  // An error occurred, we need to handle the error
                                                  // See: https://developers.facebook.com/docs/ios/errors
                                              } else {
                                                  // Success
                                                  NSLog(@"result %@", results);
                                              }
                                          }];
            
        } else {
            
            // Prepare the web dialog parameters
            NSDictionary *feedParams = @{
                                         @"name" : shareParams.name,
                                         @"link" : shareParams.link
                                         };
            
            // Invoke the dialog
            [FBWebDialogs presentFeedDialogModallyWithSession:nil
                                                   parameters:feedParams
                                                      handler:
             ^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
                 if (error) {
                     NSLog(@"Error publishing story.");
                 } else {
                     if (result == FBWebDialogResultDialogNotCompleted) {
                         NSLog(@"User canceled story publishing.");
                     } else {
                         NSLog(@"Story published.");
                     }
                 }}];
        }
    }
    
}

#pragma mark 트위터
-(void)goTwitter{
    
    mTwitter = [[TWTweetComposeViewController alloc] init];
    
    NSString *text = [NSString stringWithFormat:@"%@\n%@",[self shareOfIssueTitle],[self shareOfIssueCaption]];
    if (text.length > 100) {
        text = [text substringToIndex:100];
        text = [text stringByAppendingString:@"..."];
    }
    
    [mTwitter setInitialText:text];
    
    [mTwitter addURL:[NSURL URLWithString:[self shareOfNewsURL]]];
    [self presentModalViewController:mTwitter animated:YES];
    
    mTwitter.completionHandler = ^(TWTweetComposeViewControllerResult result){
        
        [mTwitter dismissModalViewControllerAnimated:YES];
        switch (result) {
            case SLComposeViewControllerResultCancelled:
                
                break;
            case SLComposeViewControllerResultDone:
                break;
                
            default:
                break;
        }
        
    };
}


#pragma mark - 노티
//parent에서 리스트 다 부르면 호출
-(void)loadItemLoad:(NSNotification*)notification{
    
    if (self.parentClassIndex == 3 || self.parentClassIndex == 4) {
        //사진만보기와 스키마로 넘어온건 안함
        return;
    }else if(self.parentClassIndex == 6){
        //스타랭킹에서 넘어올때
        NSArray *array = (NSArray*)[notification object];
        [self settingDataFromStar:array];
        return;
    }
    
    self.issuesList = (NSArray*)[notification object];
    
    requestType = RequestNext;
    [self addRequestDataNext:YES];
}

#pragma mark - 페이지 샛팅
-(void)settingPageToNext:(BOOL)next{
    
    [self setImageIndex:currentImageIndex andNext:next atFirst:NO];
    [self reloadPage];
}

-(void)reloadPage{
    
    if (!titleView.hidden) {
        
        if (self.issueFirstIndex <= 0 && self.currentImageIndex <= 0) {
            //첫페이지임
            leftArrowButton.hidden = YES;
        }else{
            leftArrowButton.hidden = NO;
        }
        
    }
    
    [self setContentIndex:currentImageIndex];
    [self setTitleIndex:currentImageIndex];
    if (self.parentClassIndex == 2) {
        [self setCountWinAndLose:currentImageIndex];
        [self setRankingLabel:currentImageIndex];
    }else{
        [self setCountUpandDown:currentImageIndex];
    }
}

#pragma mark - 이미지
-(void)setOnePhotoImage:(NSDictionary*)dic{
    
    NSString *domainImage = [dic objectForKey:@"imgurl"];
    NSDictionary *dataDic = [dic objectForKey:@"data"];
    
    //datalist 샛팅
    [dataList addObject:dataDic];
    
    NSString *caption = [appDelegate stringByHTMLEncodingWithString:[dataDic objectForKey:@"caption"]];
    contentTextView.text = caption;
    NSString *upStr = [dataDic objectForKey:@"up_cnt"];
    NSString *downStr = [dataDic objectForKey:@"down_cnt"];
    [self setUp:upStr andDown:downStr];

    [self setTitleIndex:0];
    
    [appDelegate loadAsyncImageFromDomain:domainImage andFileName:[dataDic objectForKey:@"thumb_url"] imageBlock:^(UIImage *image) {
        secondView.frame = framePhoto(0);
        [self initSetImage:image andImageView:sImage];
        mScrollView.scrollEnabled = NO;
        
    } errorBlock:^{
        
    }];
}

-(void)imageSetting:(NSArray*)array{
    
    return; //느려서 다른걸로 바꾸자
    //데이타 받으면 바로 이미지로컬에 저장
//    NSString *photoKey = (self.parentClassIndex == 1 || self.parentClassIndex == 5) ? @"photo_url" : @"thumb_url";
    
    
    NSMutableArray *tArray = [NSMutableArray array];
    
    for (int i = 0; i<[array count]; i++) {
        
        NSString *imageStr = [[array objectAtIndex:i] objectForKey:@"photo_url"];

        
        [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:imageStr imageBlock:^(UIImage *image) {
            [mImageDic setValue:image forKey:imageStr];
            [tArray addObject:imageStr];
            if (tArray.count >= array.count) {
                [self completeImageSetting];
            }
            
        } errorBlock:^{
            [tArray addObject:imageStr];
            if (tArray.count >= array.count) {
                [self completeImageSetting];
            }
        }];
    }
    
}

-(void)completeImageSetting{
    
//    NSLog(@"completeImageSetting : %@",mImageDic);
    
    
    //스크롤컨텐츠 샛팅
    if (requestType == RequestNext || requestType == RequestNone) {
        
    }else{
        
    }
    
}

-(void)setImageIndex:(NSInteger)index andNext:(BOOL)yn atFirst:(BOOL)first{
    
    //    mScrollView.zoomScale = 1.0f;
//    NSString *photoKey = (self.parentClassIndex == 1 || self.parentClassIndex == 5) ? @"photo_url" : @"thumb_url";
    
    NSString *photoId = [[dataList objectAtIndex:currentImageIndex] objectForKey:@"photo_id"];
    [self requestPhotorowWithPhotoID:photoId];
//    appearAD = NO;
    
    NSLog(@"<<photo index>> : %d",index);
    if (yn) {
        
        //다음것
        UIImage *nextImage = tImage.image;
        UIImage *currentImage = sImage.image;
        
        //현재 : 다음것 이미지를 현재로 가져옴
        if (nextImage && !first &&index==thirdView.tag) {
            //다음이미지가 있다면 그냥 적용 그리고 만약 서버에서 방금 불렀다면 걍 다음거, 인덱스도 맞는지 확인해야함
            secondView.frame = framePhoto(index);
            [self initSetImage:nextImage andImageView:sImage];
        }else{
            NSString *keyString = [[dataList objectAtIndex:index] objectForKey:@"photo_url"];
            UIImage *image = [mImageDic objectForKey:keyString];
            
            if (image) {
                //mImageDic에 저장이 되어있다면
                secondView.frame = framePhoto(index);
                [self initSetImage:image andImageView:sImage];
                secondView.tag = index;
            }else{
                
                //안되어있으면 부르고 딕셔너리에 저장해줌
                [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:keyString imageBlock:^(UIImage *image) {
                    
                    secondView.frame = framePhoto(index);
                    [self initSetImage:image andImageView:sImage];
                    secondView.tag = index;
                    [mImageDic setValue:image forKey:keyString];
                    //                secondView.image = image;
                } errorBlock:^{
                    
                }];
            }
        }
        
        
        //이전 : 현재것 잉미지를 이전로 가져감
        if (index-1 >= 0) {
            
            
            if (currentImage && index-1 == secondView.tag) {
                firstView.frame = framePhoto(index-1);
                //                firstView.image = currentImage;
                [self initSetImage:currentImage andImageView:fImage];
            }else{

                NSString *keyString = [[dataList objectAtIndex:index-1] objectForKey:@"photo_url"];
                UIImage *image = [mImageDic objectForKey:keyString];
                
                if (image) {
                    //mImageDic에 저장되어있다면
                    firstView.frame = framePhoto(index-1);
                    [self initSetImage:image andImageView:fImage];
                    firstView.tag = index-1;
                }
                else{
                    //안되어있다면 딕셔너리에 저장
                    [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:keyString imageBlock:^(UIImage *image) {
                        
                        //                    firstView.image = image;
                        firstView.frame = framePhoto(index-1);
                        [self initSetImage:image andImageView:fImage];
                        firstView.tag = index-1;
                        [mImageDic setValue:image forKey:keyString];
                        
                    } errorBlock:^{
                        
                    }];
                }
            }
        }
        
        
        //다음이미지는 없을테니 그냥 부름
        if (index+1 <[dataList count]) {
            
            
            NSString *keyString = [[dataList objectAtIndex:index+1] objectForKey:@"photo_url"];
            UIImage *image = [mImageDic objectForKey:keyString];
            
            if (image) {
                
                thirdView.frame = framePhoto(index+1);
                [self initSetImage:image andImageView:tImage];
                thirdView.tag = index+1;
            }else{
                
                [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:keyString imageBlock:^(UIImage *image) {
                    
                    //                thirdView.image = image;
                    thirdView.frame = framePhoto(index+1);
                    [self initSetImage:image andImageView:tImage];
                    thirdView.tag = index+1;
                    [mImageDic setValue:image forKey:keyString];
                    
                } errorBlock:^{
                    
                }];
            }
            
        }
        
        //광고관련
        currentAdCount++;
        nextPageIsMan = (currentAdCount != 0 && (int)currentAdCount%self.adCount == 0); //다음페이지가 광고페이지인지 확인
        
        
    }else{
        //이전것
        
        
        UIImage *prevImage = fImage.image;
        UIImage *currentImage = sImage.image;
        
        //현재 : 이전것 이미지를 현재로 가져옴
        if (prevImage && !first && index == firstView.tag) {
            secondView.frame = framePhoto(index);
            [self initSetImage:prevImage andImageView:sImage];
        }else{
            
            NSString *keyString = [[dataList objectAtIndex:index] objectForKey:@"photo_url"];
            UIImage *image = [mImageDic objectForKey:keyString];
            
            if (image) {
                
                [self initSetImage:image andImageView:sImage];
                secondView.frame = framePhoto(index);
                secondView.tag = index;
            }
            else{
                
                //없으면 부름
                [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:keyString imageBlock:^(UIImage *image) {
                    
                    //                secondView.image = image;
                    [self initSetImage:image andImageView:sImage];
                    secondView.frame = framePhoto(index);
                    secondView.tag = index;
                    [mImageDic setValue:image forKey:keyString];
                    
                } errorBlock:^{
                    
                }];
            }
        }
        
        //다음 : 현재 이미지는 다음으로 가져감
        if (index+1 < [dataList count]) {
            
            if (currentImage && index+1 == thirdView.tag) {
                //                thirdView.image = currentImage;
                thirdView.frame = framePhoto(index+1);
                [self initSetImage:currentImage andImageView:tImage];
            }else{
                
                NSString *keyString = [[dataList objectAtIndex:index+1] objectForKey:@"photo_url"];
                UIImage *image = [mImageDic objectForKey:keyString];
                
                if (image) {
                    
                    thirdView.frame = framePhoto(index+1);
                    [self initSetImage:image andImageView:tImage];
                    thirdView.tag = index+1;
                }else{
                    
                    [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:keyString imageBlock:^(UIImage *image) {
                        
                        //                    thirdView.image = image;
                        thirdView.frame = framePhoto(index+1);
                        [self initSetImage:image andImageView:tImage];
                        thirdView.tag = index+1;
                        [mImageDic setValue:image forKey:keyString];
                        
                    } errorBlock:^{
                        
                    }];
                }
            }
        }
        
        if (index-1 >= 0) {
            
//            if ((int)(currentAdCount-1)%self.adCount == 0) {
//                //이전페이지는 광고임
//                [self makeManBreakViewWithFrame:frameSDK(index-1)];
//            }
            
            NSString *keyString = [[dataList objectAtIndex:index-1] objectForKey:@"photo_url"];
            UIImage *image = [mImageDic objectForKey:keyString];
            
            if (image) {
                
                firstView.frame = framePhoto(index-1);
                [self initSetImage:image andImageView:fImage];
                firstView.tag = index-1;
            }else{
                
                [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:keyString imageBlock:^(UIImage *image) {
                    
                    //                firstView.image = image;
                    firstView.frame = framePhoto(index-1);
                    [self initSetImage:image andImageView:fImage];
                    firstView.tag = index-1;
                    [mImageDic setValue:image forKey:keyString];
                    
                } errorBlock:^{
                    
                }];
            }
            
        }
        
        currentAdCount--;
        prevPageIsMan = (currentAdCount != 0 && (int)currentAdCount%self.adCount == 0);
        
    }
    
    NSLog(@"adcount : %d\t%@%@",currentAdCount,nextPageIsMan?@"다음페이지 광고":@"",prevPageIsMan?@"이전페이지 광고":@"");
    
}

-(void)nextImage{
    [mScrollView setContentOffset:CGPointMake(mScrollView.contentOffset.x+mySize.width, 0) animated:YES];
}

-(void)previousImage{
    [mScrollView setContentOffset:CGPointMake(mScrollView.contentOffset.x-mySize.width, 0) animated:YES];
}

//이미지 비율&좌표 맞추기
-(void)initSetImage:(UIImage*)_image andImageView:(UIImageView*)imageView
{
    float ratio = mySize.width/mySize.height;
    float imageRatio = _image.size.width/_image.size.height;
    
    float rWidth = 0;
    float rHeight = 0;
    
    if (imageRatio > ratio) {
        //가로맞춤
        rWidth = mySize.width;
        rHeight = (mySize.width*_image.size.height)/_image.size.width;
    }else{
        //세로맞춤
        rHeight = mySize.height;
        rWidth = (mySize.height*_image.size.width)/_image.size.height;
    }
    imageView.image = _image;
    imageView.frame = CGRectMake(0, 0, rWidth, rHeight);
    imageView.center = CGPointMake(mySize.width*0.5f, mySize.height*0.5f-10);
}

#pragma mark - 전면보기
-(void)changeFullScreen{
    //1:배틀외 2:배틀 3:사진만 4:스키마+이슈 5:검색
    if (titleView.hidden) {
        if (self.analyticsAction && self.analyticsLabelDetail && self.analyticsLabelWhole) {
            
            [appDelegate analyticsCategory:ANA_CAT_PAGE Action:self.analyticsAction Label:self.analyticsLabelDetail];
        }
        titleView.hidden = bottomView.hidden = contentView.hidden = rightArrowButton.hidden = leftArrowButton.hidden = NO;
        
        if (self.issueFirstIndex <= 0 && self.currentImageIndex <= 0) {
            //첫페이지임
            leftArrowButton.hidden = YES;
        }
    }else{
        if (self.analyticsAction && self.analyticsLabelDetail && self.analyticsLabelWhole){
            [appDelegate analyticsCategory:ANA_CAT_PAGE Action:self.analyticsAction Label:self.analyticsLabelWhole];
        }
        titleView.hidden = bottomView.hidden = contentView.hidden = rightArrowButton.hidden = leftArrowButton.hidden = YES;
    }
}



-(void)addRequestDataNext:(BOOL)yn{
    
    //인덱스 구분하고 더 부를 데이타 있다면 부름
    if (yn) {
        //다음페이지
        
        if (self.typeHotIssue) {
            //핫이슈일때 마지막이슈를 부를시 가장 처음의 이슈를 호출
            self.issueLastIndex = (self.issueLastIndex+1 < [self.issuesList count]) ? self.issueLastIndex+1 : 0;
            loadIndex = self.issueLastIndex;
        }else{
            
            //스타에서 넘어왔을때
            if (self.parentClassIndex == 6) {
                //stars.php page++ load
                if ([self.mDelegate respondsToSelector:@selector(loadNextPage)] && self.parentClassIndex != 3 && self.parentClassIndex == 4) {
                    [self.mDelegate performSelector:@selector(loadNextPage)];
                }else{
                    
                    [appDelegate alertViewWithMessage:NSLocalizedString(@"Last page", @"") andTimeInterval:2.0f];
                }
                return;
                
            }else{
                
                //일반일때
                if (self.issueLastIndex+1 < [self.issuesList count]) {
                    loadIndex = self.issueLastIndex+1;
                }else{
                    //이슈리스트 다음걸 불러야함
                    
                    if ([self.mDelegate respondsToSelector:@selector(loadNextPage)] && self.parentClassIndex != 3 && self.parentClassIndex == 4) {
                        [self.mDelegate performSelector:@selector(loadNextPage)];
                    }else{
                        
                        [appDelegate alertViewWithMessage:NSLocalizedString(@"Last page", @"") andTimeInterval:2.0f];
                    }
                    
                    return;
                }
            }
        }
    }else{
        //이전페이지
        if (self.typeHotIssue) {
            self.issueFirstIndex = (self.issueFirstIndex-1 < 0) ? [self.issuesList count]-1 : self.issueFirstIndex-1;
            loadIndex = self.issueFirstIndex;
        }else{
            if (issueFirstIndex-1 >= 0) {
                loadIndex = self.issueFirstIndex-1;
            }else{
                //안부름
                [appDelegate alertViewWithMessage:NSLocalizedString(@"First page", @"") andTimeInterval:2.0f];
                return;
            }
        }
    }
    //이슈 부르기
    
    if (self.parentClassIndex == 1) {
        
        NSString *issueID = [[self.issuesList objectAtIndex:loadIndex] objectForKey:@"issue_id"];
        [self requestIssueID:issueID];
    }else if(self.parentClassIndex == 2){
        NSString *starID = [[self.issuesList objectAtIndex:loadIndex] objectForKey:@"star_id"];
        [self requestBattleWithDate:self.dateString andStarID:starID];
    }else if(self.parentClassIndex == 5){
        
        NSString *contentID = [[self.issuesList objectAtIndex:loadIndex] objectForKey:@"content_id"];
        [self requestIssueID:contentID];
    }
}

#pragma mark - 팝업

-(void)removeAlertView:(NSTimer*)timer
{
    UIAlertView *backview = (UIAlertView *)[timer userInfo];
    [backview dismissWithClickedButtonIndex:0 animated:YES];
}

#pragma mark - 광고

-(void)makeManBreakInImageViewComeLeft:(BOOL)yn {
    
    [appDelegate appearActivityOnPoint:CGPointMake(mySize.width*0.5f, mySize.height*0.5)];
    
    if (!manBreak) {
        
        manBreak = [[ManBreakAdView alloc] initWithFrame:CGRectMake(0, myOrginY, mySize.width, mySize.height-20)];
    }
    mComeLeft = yn;
    manBreak.frame = yn ? frameSDK_L : frameSDK_R;
    manBreak.delegate = self;
    [manBreak applicationID:@"dispatch/dispatch" adWindowId:@"interstitial2"];
    [self.view addSubview:manBreak];
    [manBreak setBShowEndAnimation:NO];
    [manBreak startBreakAd];
    
}

-(void)makeManBreakViewWithFrame:(CGRect)frame{
    
    [appDelegate appearActivityOnPoint:CGPointMake(mySize.width*0.5f, mySize.height*0.5)];
    
    if (!manBreak) {
        
        manBreak = [[ManBreakAdView alloc] init];
        [mScrollView addSubview:manBreak];
    }
    manBreak.frame = frame;
    //    manBreak.frame = yn ? frameSDK_L : frameSDK_R;
    manBreak.delegate = self;
    [manBreak applicationID:@"dispatch/dispatch" adWindowId:@"interstitial2"];
    [manBreak setBShowEndAnimation:NO];
    [manBreak startBreakAd];
    
}

-(void)passManSDK:(BOOL)bComeLeft{
    
    appearAD = NO;
    [self photoLeftMove:bComeLeft];
    CGRect rect;
    rect = bComeLeft ? CGRectMake(mySize.width, 0, mySize.width, mySize.height-20) : CGRectMake(-mySize.width, 0, mySize.width, mySize.height-20);
    [UIView animateWithDuration:0.3f animations:^{
        manBreak.frame = rect;
    } completion:^(BOOL finished) {
        if (manBreak) {
            if ([manBreak superview]) {
                [manBreak removeFromSuperview];
                manBreak = nil;
            }
        }
        
    }];
}

-(void)photoLeftMove:(BOOL)yn{
    
    if (yn) {
        if (mComeLeft) {
            //왼쪽에서 튀어나왔던 광고
            currentImageIndex--;
        }
    }else{
        if (!mComeLeft) {
            //오른쪽에서 튀어나왔던 광고
            currentImageIndex++;
        }
    }
//    if (requestType == RequestNone) {
    
        [mScrollView setContentOffset:CGPointMake(mySize.width*currentImageIndex, 0) animated:YES];
//    }
}

#pragma mark Delegate

-(void)didSwipeBreakAd:(BOOL)bLeftSwipe{
    
    [self passManSDK:!bLeftSwipe];
}

-(void)didWebLoadBreakAd{
    
    [appDelegate removeActivity];
    //완료
    [UIView animateWithDuration:0.3f animations:^{
        manBreak.frame = frameSDK_C;
    } completion:^(BOOL finished) {
        appearAD = NO;
    }];
}

-(void)didFailWebLoadBreakAd{
    
    [self passManSDK:mComeLeft];
}

-(void)didCloseBreakAd{
    
    [self passManSDK:mComeLeft];
}

-(void)didClickBreakAd{
    
    [self passManSDK:mComeLeft];
}

-(void)didFailBreakAd{
    
    [self passManSDK:mComeLeft];
}


#pragma mark - 네트워크

-(void)requestIssueID:(NSString*)issueID{

    if (duringNetwork) {
        //로딩중
        return;
    }
    
    requestIndex = 1;
    [appDelegate appearActivityOnPoint:CGPointMake(mySize.width*0.5f, mySize.height*0.5f)];
    NSString *dataStr = [NSString stringWithFormat:@"id=%@&lang=%@&deviceid=%@",issueID,appDelegate.currentLanguage,[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"]];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *stringURL = [NSString stringWithFormat:@"%@?p=%@",URL_ISSUE,dataStr];
    [self requestURL:stringURL];
    
    [mActivityView startAnimating];
}

-(void)requestIssueID:(NSString*)issueID andPushID:(NSString*)pushID{
    
    if (duringNetwork) {
        return;
    }
    requestIndex = 1;
    
    [appDelegate appearActivityOnPoint:CGPointMake(mySize.width*0.5f, mySize.height*0.5f)];
    NSString *dataStr = [NSString stringWithFormat:@"id=%@&lang=%@&pid=%@&os=ios&route=pns&deviceid=%@",issueID,appDelegate.currentLanguage,pushID,[[NSUserDefaults standardUserDefaults]objectForKey:@"uuid"]];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *stringURL = [NSString stringWithFormat:@"%@?p=%@",URL_ISSUE,dataStr];
    [self requestURL:stringURL];
    
    [mActivityView startAnimating];
}

-(void)requestBattleWithDate:(NSString*)date andStarID:(NSString*)starID{
    
    if (duringNetwork) {
        return;
    }
    
    [appDelegate appearActivityOnPoint:CGPointMake(mySize.width*0.5f, mySize.height*0.5f)];
    requestIndex = 1;
    NSString *dataStr = [NSString stringWithFormat:@"star_id=%@&date=%@&lang=%@",starID,date,appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *stringURL = [NSString stringWithFormat:@"%@?p=%@",URL_BATTLE_DETAIL,dataStr];
    [self requestURL:stringURL];
    
    [mActivityView startAnimating];
}

-(void)requestUp:(BOOL)up andIssueID:(NSString*)issueID{
    
    if (duringNetwork) {
        return;
    }
    
    [appDelegate appearActivityOnPoint:CGPointMake(mySize.width*0.5f, mySize.height*0.5f)];
    requestIndex = 2;
    NSString *dataStr = [NSString stringWithFormat:@"deviceid=%@&type=%d&issue_id=%@&lang=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"],up?1:2,issueID,appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *stringURL = [NSString stringWithFormat:@"%@?p=%@",URL_UP_DOWN,dataStr];
    
    [self requestURL:stringURL];
}

-(void)requestPhotorowWithPhotoID:(NSString*)photoID{
    if (duringNetwork) {
        return;
    }
    
    NSString *dataStr = [NSString stringWithFormat:@"id=%@&lang=%@",photoID,appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *stringURL = [NSString stringWithFormat:@"%@?p=%@",URL_PHOTOROW,dataStr];
    [self requestURL:stringURL];
}

-(void)requestURL:(NSString*)url{
    
    [self performSelectorOnMainThread:@selector(startRequestWithURL:) withObject:url waitUntilDone:NO];
}

-(void)startRequestWithURL:(NSString*)url{
    @autoreleasepool {
        
        duringNetwork = YES;
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        if (url) {
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
            [request setHTTPMethod:@"POST"];
            
            
            NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

            if(connection){
                NSLog(@"기사상세 네트워크 요청 : %@",url);
//                [appDelegate appearActivityOnPoint:CGPointMake(mySize.width*0.5f, mySize.height*0.5f)];
            }
            
        }
    }
}

#pragma mark delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connectio{
    
    [appDelegate removeActivity];
    duringNetwork = NO;
    
    NSString *currentRequestString = [NSString stringWithFormat:@"%@",connectio.currentRequest];
    
    if ([currentRequestString rangeOfString:URL_PHOTOROW].location != NSNotFound) {
//        [appDelegate removeActivity];

        return;
    }
    
    [mActivityView stopAnimating];
    
    NSError *myError = nil;
    NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
    self.imageURL = ([appDelegate checkObject:[resultDictionary objectForKey:@"imgurl"]]) ? [resultDictionary objectForKey:@"imgurl"] : nil;
    NSLog(@"기사상세 : %@",resultDictionary);
    
    if (requestIndex == 1) {
        if ([resultDictionary objectForKey:@"return_code"]) {
            if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0){
                
                NSArray *items;
                if (self.parentClassIndex == 2) {
                    //배틀일떄
                    items = [NSArray arrayWithObject:[resultDictionary objectForKey:@"data"]];

                }else{
                    items = [[resultDictionary objectForKey:@"data"] objectForKey:@"items"];
                }
                
                float offsetX = 0.0f;
                NSInteger offsetIndex = 0;
                
//                [self settingToPhotoDataWithArray:items]; //이따 확인해보자
                
                ///*
                if (requestType == RequestNext || requestType == RequestNone) {
                    NSLog(@"다음이슈 요청 RequestNext");
                    offsetX = dataList.count*mySize.width;
                    [dataList addObjectsFromArray:items];
                    float width = (dataList.count <= 1) ? (mySize.width*dataList.count)+10 : mySize.width*dataList.count;
                    [mScrollView setContentSize:CGSizeMake(width, mScrollView.frame.size.height)];
                    [mScrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
                    currentScrollContentSize = width;
                    
                    self.issueLastIndex = loadIndex;
                    
                }else if(requestType == RequestPrevious){
                    NSLog(@"이전이슈 요청 RequestPrevious");
                    offsetX = (items.count*mySize.width)-mySize.width;
                    NSIndexSet *idxSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [items count])];
                    [dataList insertObjects:items atIndexes:idxSet];
                    float width = (dataList.count <= 1) ? (mySize.width*dataList.count)+10 : mySize.width*dataList.count;
                    
                    
                    [mScrollView setContentSize:CGSizeMake(width, mScrollView.frame.size.height)];
                    secondView.frame = framePhoto(items.count);
                    
                    [mScrollView setContentOffset:CGPointMake(items.count*mySize.width, 0)];
                    [mScrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
                    
                    currentScrollContentSize = width;
                    
                    self.issueFirstIndex = loadIndex;
                    
                }
                
                
                
                self.currentImageIndex = (int)offsetX/mySize.width;
                
                [self setImageIndex:currentImageIndex andNext:(requestType == RequestNext || requestType == RequestNone) atFirst:YES];
                [self reloadPage];
                

            }
        }
    }else if(requestIndex == 2){
        
        [appDelegate removeActivity];
        
        if ([resultDictionary objectForKey:@"return_code"]) {
            if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0){
                
                resultDictionary = [resultDictionary objectForKey:@"data"];
                int type = [[resultDictionary objectForKey:@"vote_status"] intValue];
                NSString *message = (type == 1) ? NSLocalizedString(@"upSuccess", @"") : NSLocalizedString(@"downSuccess", @"");
                [appDelegate alertViewWithMessage:message andTimeInterval:2.0f];
                
                NSString *up = [resultDictionary objectForKey:@"up_cnt"];
                NSString *down = [resultDictionary objectForKey:@"down_cnt"];
                
                
                //해놓은거 임시저장
                if (!upDownTSDic) {
                    upDownTSDic = [[NSMutableDictionary alloc] init];
                }
                [upDownTSDic setValue:[NSNumber numberWithInt:type]
                               forKey:[[dataList objectAtIndex:currentImageIndex] objectForKey:@"issue_id"]];
                
                
                upCountLabel.text = up;
                downCountLabel.text = down;
                if (type == 1) {
                    upButton.selected = YES;
                }else if (type == 2){
                    downButton.selected = YES;
                }
                
//                [self setUp:up andDown:down];
                [appDelegate removeActivity];
                
            }else if([[resultDictionary objectForKey:@"return_code"] intValue] == 1){
                //이미참여함
                [appDelegate alertViewWithMessage:NSLocalizedString(@"upOrDownFail", @"") andTimeInterval:2.0f];
            }
        }
    }else{
        [appDelegate removeActivity];
    }
    
    
    
    
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    duringNetwork = NO;
    NSLog(@"이슈리스트 네트워크 요청 실패 : %@",error);
    [appDelegate alertViewWithMessage:@"request failed" andTimeInterval:2.0f];
    [appDelegate removeActivity];
    [mActivityView stopAnimating];
    
    
}



#pragma mark - UIScrollView Delegate

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
//    NSLog(@"scrollViewDidEndDragging : %d",(NSInteger)(mScrollView.contentOffset.x/mySize.width));
}

-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    
    if (deviceIOS7) {
        
        if (!zooming) {
            firstView.hidden = thirdView.hidden = NO;
            
            if (self.parentClassIndex == 4 || self.parentClassIndex == 3) {
                return;
            }
            
            if (scrollView.contentOffset.x > scrollView.contentSize.width-mySize.width) {
                //댜음 것 부르기
                requestType = RequestNext;
                [self addRequestDataNext:YES];
                
            }else if(scrollView.contentOffset.x < 0){
                requestType = RequestPrevious;
                [self addRequestDataNext:NO];
            }else{
                requestType = RequestNone;
            }
        }
    }
}

-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    
    if (!deviceIOS7) {
        
        if (!zooming) {
            firstView.hidden = thirdView.hidden = NO;
            
            if (self.parentClassIndex == 4 || self.parentClassIndex == 3) {
                return;
            }
            
            if (scrollView.contentOffset.x > scrollView.contentSize.width-mySize.width) {
                
                //댜음 것 부르기
                requestType = RequestNext;
                [self addRequestDataNext:YES];
                
            }else if(scrollView.contentOffset.x < 0){
                requestType = RequestPrevious;
                [self addRequestDataNext:NO];
            }else{
                requestType = RequestNone;
            }
        }
    }

}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

    if (!zooming) {
        
        firstView.hidden = thirdView.hidden = NO;
        
        NSInteger offsetIndex = (int)(scrollView.contentOffset.x/mySize.width);

        
        if ((int)offsetIndex != currentImageIndex) {
            if (currentImageIndex > offsetIndex) {
                currentImageIndex = offsetIndex;
                
                [self settingPageToNext:NO];
                
            }else if(currentImageIndex < offsetIndex){
                currentImageIndex = offsetIndex;
                
                [self settingPageToNext:YES];
            }
        }
    }
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    NSLog(@"scrollView.x : %f",scrollView.contentOffset.x);

    if (!zooming) {
        
        firstView.hidden = thirdView.hidden = NO;
        
        if (self.parentClassIndex == 4) {
            return;
        }
        
        if (currentImageIndex == [dataList count]-1 && scrollView.contentOffset.x > scrollView.contentSize.width-mySize.width) {
            [scrollView setContentOffset:CGPointMake(scrollView.contentSize.width-mySize.width+10, 0)];
        }else if(currentImageIndex == 0 && scrollView.contentOffset.x < 0){
            [scrollView setContentOffset:CGPointMake(-10, 0)];
        }
        
        if (self.parentClassIndex != 3 && self.parentClassIndex != 4) {
            
            if (nextPageIsMan && scrollView.contentOffset.x > mySize.width*currentImageIndex) {
                if (!appearAD) {
                    appearAD = YES;
                    NSLog(@"광고띄움 1");
                    [self makeManBreakInImageViewComeLeft:NO];
                }
                [scrollView setContentOffset:CGPointMake(mySize.width*currentImageIndex, 0)];
            }else if (prevPageIsMan){
                if (!appearAD) {
                    appearAD = YES;
                    NSLog(@"광고띄움 2");
                    [self makeManBreakInImageViewComeLeft:YES];
                }
                [scrollView setContentOffset:CGPointMake(mySize.width*currentImageIndex, 0)];
            }
        }
        
    }
    
    
}

-(void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view{
    
    
    firstView.hidden = thirdView.hidden = YES;
    zooming = YES;
    secondView.frame = CGRectMake(0, 0, secondView.frame.size.width, secondView.frame.size.height);
    
    CGPoint point = CGPointMake(currentImageIndex*mySize.width, 0);
    CGPoint offset = mScrollView.contentOffset;
    
    if (offset.x == point.x && offset.y == point.y) {
        [mScrollView setContentOffset:CGPointMake(0, 0)];
    }
    
}

-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    
    
    return secondView;

}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale{
    
    if (scale == 1.0f) {
        
        zooming = NO;
        [mScrollView setContentSize:CGSizeMake(currentScrollContentSize, scrollView.frame.size.height)];
        secondView.frame = framePhoto(currentImageIndex);
        [mScrollView setContentOffset:CGPointMake(currentImageIndex*mySize.width, 0)];
    }
}

#pragma mark - UIAction Sheet Delegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    switch (buttonIndex) {
        case 0:
            //카카오톡
            [self goKakaoTalk];
            break;
            
        case 1:
            //카카오스토리
            [self goKakaoStory];
            break;
            
        case 2:
            //페북
            [self goFaceBook];
            break;
        case 3:
            //트위터
            [self goTwitter];
            break;
            
        default:
            break;
    }
}



#pragma mark - 스타에서 넘어올때 데이타 받음
-(void)settingDataFromStar:(NSArray*)starArray{
    
    
    self.issueFirstIndex = 0;
    self.issueLastIndex = 0;
    [self settingToPhotoDataWithArray:starArray];
}

-(void)settingToPhotoDataWithArray:(NSArray*)items{
    
    [appDelegate appearActivityOnPoint:CGPointMake(mySize.width*0.5f, mySize.height*0.5f)];
    
    [dataList addObjectsFromArray:items];
    float width = mySize.width*dataList.count;
    currentScrollContentSize = width;
    
    [mScrollView setContentSize:CGSizeMake(mySize.width*items.count, mScrollView.frame.size.height)];
    [mScrollView setContentOffset:CGPointMake(mySize.width*currentImageIndex, 0)];
    [self setImageIndex:currentImageIndex andNext:YES atFirst:YES];
    
    [self reloadPage];
}




@end
